package com.jy.api.service.impl;import com.fasterxml.jackson.databind.ObjectMapper;import com.jy.api.config.WebSocketUrlUtils;import com.jy.api.dao.*;import com.jy.api.domain.*;import com.jy.api.enums.OrderPayChannel;import com.jy.api.enums.PayTypeEnum;import com.jy.api.pay.request.PayRequest;import com.jy.api.payReq.*;import com.jy.api.payRes.SuiXinFuCallBackRes;import com.jy.api.service.*;import com.jy.api.signUpReq.web.WebCancelPayReq;import com.jy.api.util.*;import com.jy.api.vo.admin.payment.PaymentVo;import com.thoughtworks.xstream.XStream;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.BeanUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.http.ResponseEntity;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.messaging.simp.SimpMessagingTemplate;import org.springframework.stereotype.Service;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;import org.springframework.web.client.ResourceAccessException;import org.springframework.web.client.RestTemplate;import javax.annotation.Resource;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.math.BigDecimal;import java.util.*;@Slf4j@Servicepublic class PaymentServiceImpl implements PaymentService {    @Autowired    HuiFuServiceImpl huiFuService;    private PaymentDao paymentDao;    private OrderDao orderDao;    private MemberService memberService;    private StoreDao storeDao;    private WechatTemplateService wechatTemplateService;    private AliyunMNSSend aliyunMNSSend;    private RestTemplate restTemplate;    private TransactionTemplate transactoinTemplate;    private StockService stockService;    private MemberDao memberDao;    private MemberAccountDao memberAccountDao;    private SimpMessagingTemplate simpMessagingTemplate;    private ObjectMapper objectMapper;    private XStream xstream;    private JdbcTemplate jdbc;    private MemberAccountTransactionDao memberAccountTransactionDao;    private StockTransactionService stockTransactionService;    private MemberAccountService memberAccountService;    @Autowired    private RewardDao rewardDao;    @Autowired    private EmployeeDao e;    @Autowired    private MemberTeamAccountDao memberTeamAccountDao;    @Autowired    private SuiXinFuServiceImpl suiXinFuService;    @Autowired    private StockOrderShopDao shopDao;    @Autowired    private StorePayDao storePayDao;    @Autowired    private SaoBeiServiceImpl saoBeiService;    @Value("${api.gateway.url}")    private String baseURL;    @Autowired    private AliyunProducerClient aliyunProducerClient;    @Autowired    private AccountBalanceDao accountBalanceDao;    @Autowired    private CallTranDao callTranDao;    @Autowired    private TeamTransactionDao teamTransactionDao;    @Autowired    private RedisSyncLocker redisSyncLocker;    @Autowired    private StringRedisTemplate redisTemplate;    @Autowired    private WebSocketUrlUtils urlUtils;    @Autowired    private HSServiceImpl hsService;    @Autowired    private JLServiceImpl jlService;    @Autowired    private DiscountOrderItemDao discountOrderItemDao;    @Autowired    private DiscountPromotionProductDao discountPromotionProductDao;    @Autowired    private CouponInstanceDao couponInstanceDao;    @Resource    private CouponInstanceService couponInstanceService;    @Resource    private RedisService redisService;    @Autowired    private MakeOrderItemDao makeOrderItemDao;    @Autowired    private MakeOrderDao makeOrderDao;    @Autowired    private LeaseProductOrderDao leaseProductOrderDao;    @Autowired    private LeaseProductDao leaseProductDao;    @Override    public SwiftPassReversePaymentResult cancelThirdPartyPayment(String orderId, WebCancelPayReq req) throws Exception {        return (SwiftPassReversePaymentResult) redisSyncLocker.idLock(orderId, new ISyncExecutor() {            @Override            public Object execute(Object o) throws Exception {                Order order = orderDao.findOne(orderId);                Reward reward = rewardDao.findOne(orderId);                log.info("门店{}, 订单号{}, 操作{}, 操作内容{}, reward:{}", order.getStoreId(), order.getId(), "取消订单开始", order, reward);                if (reward != null) {                    if (reward.getStatus().equals(OrderStatus.CANCELED)) {                        log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "该笔支付已经被取消");                        throw new RuntimeException("该笔支付已经被取消");                    } else if (reward.getStatus().equals(OrderStatus.UNFINISHED) || reward.getStatus().equals(OrderStatus.FINISHED)) {                        log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "已经成功支付，取消支付操作被中止。");                        throw new RuntimeException("已经成功支付，取消支付操作被中止。");                    } else {                        Store store = storeDao.findOne("574b59ef-b19c-11e7-9233-37891743d141");                        AllPayBaseResult paymentResult = queryMicroPay(reward.getId());                        if (paymentResult.isSuccess()) {                            log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "已经成功支付，取消支付操作被中止(火星云)。");                            throw new RuntimeException("已经成功支付，取消支付操作被中止。");                        }                        log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "优先调用撤消订单接口");                        AllPayReverseResult result = reversePayment(store.getMchId(), reward.getId(), store.getKey(), req);                        if (result.isSuccess()) {                            transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                                @Override                                protected void doInTransactionWithoutResult(TransactionStatus status) {                                    reward.setStatus(OrderStatus.INIT);                                    rewardDao.save(reward);                                }                            });                            log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "撤消成功");                            return result;                        } else {                            log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "撤消失败调用关闭订单接口");                            // 撤销失败，调用关闭订单接口                            result = closePayment(store.getMchId(), reward.getId(), store.getKey());                            if (result.isSuccess()) {                                transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                                    @Override                                    protected void doInTransactionWithoutResult(TransactionStatus status) {                                        reward.setStatus(OrderStatus.INIT);                                        rewardDao.save(reward);                                    }                                });                                log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "调用关闭订单接口成功");                                return result;                            } else {                                log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "调用关闭订单接口失败：" + result.getErrMsg());                                throw new RuntimeException(result.getErrMsg());                            }                        }                    }                } else {                    if (order.getStatus().equals(OrderStatus.CANCELED)) {                        log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "支付已经被取消，请到订单列表查询确认");                        throw new RuntimeException("支付已经被取消，请到订单列表查询确认");                    } else if (order.getStatus().equals(OrderStatus.UNFINISHED) || order.getStatus().equals(OrderStatus.FINISHED)) {                        log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "订单已经成功支付，取消支付操作被中止。请到订单列表查询确认");                        throw new RuntimeException("订单已经成功支付，取消支付操作被中止。请到订单列表查询确认");                    } else {                        Store store = storeDao.findOne(order.getStoreId());                        AllPayBaseResult paymentResult = queryMicroPay(orderId);                        if (paymentResult.isSuccess()) {                            log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "订单已经成功支付，取消支付操作被中止。请到订单列表查询确认2");                            throw new RuntimeException("订单已经成功支付，取消支付操作被中止。请到订单列表查询确认");                        }                        // 先调用撤销订单接口                        log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "优先调用撤消订单接口");                        AllPayReverseResult result = reversePayment(store.getMchId(), orderId, store.getKey(), req);                        if (result.isSuccess()) {                            transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                                @Override                                protected void doInTransactionWithoutResult(TransactionStatus status) {                                    order.setStatus(OrderStatus.CANCELED);                                    orderDao.save(order);                                }                            });                            log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "撤消成功");                            return result;                        } else {                            log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "撤消失败调用关闭订单接口");                            // 撤销失败，调用关闭订单接口                            result = closePayment(store.getMchId(), orderId, store.getKey());                            if (result.isSuccess()) {                                transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                                    @Override                                    protected void doInTransactionWithoutResult(TransactionStatus status) {                                        order.setStatus(OrderStatus.CANCELED);                                        orderDao.save(order);                                    }                                });                                log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "调用关闭订单接口成功");                                return result;                            } else {                                log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "取消订单", "调用关闭订单接口失败：" + result.getErrMsg());                                throw new RuntimeException("取消支付失败，请稍后再试");                            }                        }                    }                }            }        });    }    public AllPayReverseResult closePayment(String mchId, String orderId, String key) {        PayRequest payRequest = new PayRequest(PayTypeEnum.UNIFIED_TRADE_CLOSE.getCode(), mchId, orderId);        payRequest.setSign_agentno("10100000284");        payRequest.setUpSign(objectMapper.convertValue(payRequest, Map.class), key);        String requestBody = payRequest.toXML();        log.info("The request body of close payment is:{}", requestBody);        String xml = "";        try {            xml = OkHttpUtils.xmlPost(Payutils.ALI_QR_CODE, payRequest.toXML());        } catch (IOException e1) {            e1.printStackTrace();        }        log.info("The response body of close payment is:{}", xml);        return (AllPayReverseResult) xstream.fromXML(xml, new AllPayReverseResult());    }    public AllPayReverseResult reversePayment(String mchId, String orderId, String key, WebCancelPayReq req) {        PayRequest payRequest;        if (null == req.getSource()) {            payRequest = new PayRequest(PayTypeEnum.UNIFIED_MICROPAY_REVERSE.getCode(), mchId, orderId);        } else {            if (StringUtils.equals(req.getSource(), "PC")) {                payRequest = new PayRequest(PayTypeEnum.UNIFIED_WEIXIN_OR_ALPAY_CLOSE.getCode(), mchId, orderId);            } else {                payRequest = new PayRequest(PayTypeEnum.UNIFIED_MICROPAY_REVERSE.getCode(), mchId, orderId);            }        }        payRequest.setUpSign(objectMapper.convertValue(payRequest, Map.class), key);        // String requestBody = payRequest.toXML();        log.info("The request body of reverse payment is:{}", payRequest.toXML());        //   String xml = restTemplate.postForEntity(Payutils.ALI_QR_CODE, requestBody, String.class).getBody();        log.info("The response body of reverse payment is:{}", payRequest.toXML());        String xml = "";        try {            xml = OkHttpUtils.xmlPost(Payutils.ALI_QR_CODE, payRequest.toXML());        } catch (IOException e1) {            e1.printStackTrace();        }        return (AllPayReverseResult) xstream.fromXML(xml, new AllPayReverseResult());    }    @Override    public PaymentVo getNetCostTotal(String storeId, Date start, Date end) {        String sql = "SELECT COALESCE(sum(b.`sales_price`), 0) amount FROM `order` a LEFT JOIN " +                "`order_item` b ON a.`id`=b.`order_id`  " +                " WHERE a.`payment_time` > ? AND a.`payment_time` <= ? AND a.`store_id` =? AND (a.status = 'FINISHED' OR a.status='UNFINISHED') AND a.type='SALES' " +                "  AND b.`product_type_id` ='1' AND b.`enabled` =1";        double amount = jdbc.queryForObject(sql, Double.class, start, end, storeId);        PaymentVo paymentVo = new PaymentVo();        paymentVo.setCashAmount((int) amount * 100);        return paymentVo;    }    @Override    public PaymentVo getNetCostTotalTag(String storeId, Date start, Date end, String tag) {        String sql = "SELECT COALESCE(sum(b.`sales_price`), 0) amount FROM `order` a LEFT JOIN " +                "`order_item` b ON a.`id`=b.`order_id`  " +                " WHERE a.`payment_time` > ? AND a.`payment_time` <= ? AND a.`store_id` =? AND (a.status = 'FINISHED' OR a.status='UNFINISHED') and  a.`mobile_tag` =? AND a.type='SALES' " +                "  AND b.`product_type_id` ='1' AND b.`enabled` =1";        double amount = jdbc.queryForObject(sql, Double.class, start, end, storeId, tag);        PaymentVo paymentVo = new PaymentVo();        paymentVo.setCashAmount((int) amount * 100);        return paymentVo;    }    @Override    public AllPayBaseResult microPay(String orderId, String authCode) throws Exception {        return (AllPayBaseResult) redisSyncLocker.idLock(orderId, new ISyncExecutor() {            @Override            public Object execute(Object o) throws Exception {                Order order = orderDao.findOne(orderId);                order.setPayChannel(OrderPayChannel.SUI_XIN_FU);                order.setStatus(OrderStatus.NOTSURE);                //处理订单号                String s = UuidUtil.getUuid();                String appendStr = s.substring(s.length() - 4);                order.setPayOrderId(appendStr + order.getId());                aliyunMNSSend.sendClint(order.getPayOrderId());                // 向中信发起支付请求                orderDao.save(order);                log.info("门店{}, 订单号{}, 操作{}, 订单内容{}", order.getStoreId(), order.getId(), "进入消息队列", order);                Store store = storeDao.findOne(order.getStoreId());                StorePay storePay = storePayDao.findByStoreIdAndStartEnabled(order.getStoreId(), true);                AllPayBaseResult payResult = new AllPayBaseResult();                switch (storePay.getChannel()) {                    case JL:                        payResult = jlService.jlPay(order, authCode, storePay, store);                        break;                    case HUI_SHANG:                        payResult = hsService.HuiShangPay(order, authCode, store, storePay.getMchId());                        break;                    case SAO_BEI:                        payResult = saoBeiService.finalSaoBeiPay(order, authCode, storePay, store);                        break;                    case HUI_FU:                        payResult = huiFuService.finalHuiFuPay(order, authCode, storePay, store);                    case SUI_XIN_FU:                        payResult = suiXinFuService.suiXinFuPay(order, authCode, store, storePay.getMchId());                }              /*  log.info("门店{}, 订单号{}, 操作{}, 支付结果{}", order.getStoreId(), order.getId(), "进入消息队列", payResult);                aliyunMNSSend.sendClint(order.getId());*/                return payResult;            }        });    }    public Payment createPaymentBySwiftPassResult(SwiftPassBaseResult payResult, String storeId) {        Payment payment = new Payment();        // 使用平台交易号作为支付记录的主键，避免在线支付结果被重复保存        payment.setId(UuidUtil.getUuid());        payment.setAmount(payResult.getTotalFee() / 100.0);        payment.setChannel(payResult.getTradeType());        if (StringUtils.isNotEmpty(payResult.getTimeEnd())) {            Date paymentTime = MyDateUtils.getDateFormatDd(payResult.getTimeEnd(), "yyyyMMddHHmmss");            payment.setCreateTime(paymentTime);        }        payment.setOrderId(payResult.getOutTradeNo().substring(4));        payment.setStatus(PaymentStatus.SUCCESS);        payment.setSuccess(true);        payment.setStoreId(storeId);        return payment;    }    /**     * 支付成功事件的所有后续操作。比如商品出库、会员积分、消费通知等     *     * @param order     * @param store     */    public void postPaymentSuccess(Order order, Store store) throws Exception {        if (order.getType().equals(OrderType.SALES)) {            // 销售订单扣库存            stockService.stockOutByOrderId(order.getId());            // 发送消费通知            wechatTemplateService.sendWechatMemberSales(order);        } else if (order.getType().equals(OrderType.MEMBER_DEPOSIT)) {            memberAccountService.recharge(order);            MemberTeamAccount teamAccount;            Member member = memberDao.findOne(order.getMemberId());            TeamTransaction teamTransaction = teamTransactionDao.findByStoreIdAndEnable(store.getId(), true);            // 发送会员充值通知            if (teamTransaction != null) {                teamAccount = memberTeamAccountDao.findByMemberIdAndEnabledAndTeamId(order.getMemberId(), true, teamTransaction.getTeamId());                if (teamAccount != null) {                    teamAccount.setPoints(teamAccount.getPoints() + order.getAmount());                    memberTeamAccountDao.save(teamAccount);                    memberService.addPointByAmount(order.getMemberId(), order.getAmount(), order.getDiscount());                    wechatTemplateService.sendMemberDepositMessage(member.getCode(), store.getName(), order.getAmount(), teamAccount.getAmount(), order.getDiscount(), member.getOpenId(), order.getId());                    log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "支付成功会员充值", "对应会员" + member + "对应会员账户" + teamAccount);                } else {                    MemberAccount account = memberAccountDao.getStoreIdAndMemberId(store.getId(), order.getMemberId());                    account.setPoints(account.getPoints() + (int) order.getAmount());                    memberAccountDao.save(account);                    memberService.addPointByAmount(order.getMemberId(), order.getAmount(), order.getDiscount());                    wechatTemplateService.sendMemberDepositMessage(member.getCode(), store.getName(), order.getAmount(), account.getTotalAmount(), order.getDiscount(), member.getOpenId(), order.getId());                    log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "支付成功会员充值", "对应会员" + member + "对应会员账户" + account);                }            } else {                MemberAccount account = memberAccountDao.getStoreIdAndMemberId(store.getId(), order.getMemberId());                account.setPoints(account.getPoints() + (int) order.getAmount());                memberAccountDao.save(account);                memberService.addPointByAmount(order.getMemberId(), order.getAmount(), order.getDiscount());                wechatTemplateService.sendMemberDepositMessage(member.getCode(), store.getName(), order.getAmount(), account.getTotalAmount(), order.getDiscount(), member.getOpenId(), order.getId());                log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "支付成功会员充值", "对应会员" + member + "对应会员账户" + account);            }        }        List<DiscountOrderItem> discountOrderItems = discountOrderItemDao.findByOrderId(order.getId());        List<DiscountPromotionProduct> discountPromotionProducts = new ArrayList<>();        for (DiscountOrderItem item : discountOrderItems) {            item.setPayTime(order.getPaymentTime());            DiscountPromotionProduct promotionProduct = discountPromotionProductDao.findByProductIdAndPromotionId(item.getProductId(), item.getPromotionId());            promotionProduct.setCount(promotionProduct.getCount() + item.getQty());            discountPromotionProducts.add(promotionProduct);        }        discountPromotionProductDao.save(discountPromotionProducts);        discountOrderItemDao.save(discountOrderItems);        if (order.getStatus().equals(OrderStatus.UNFINISHED)) {            notifyPOSNewOrderArrival(order);        }        MakeOrder makeOrder = makeOrderDao.findByOrderId(order.getId());        if (order.getStatus().equals(OrderStatus.FINISHED) && null != makeOrder && makeOrder.getItems().size() > 0) {            notifyMakeTypeNewOrderArrival(order.getStoreId());        }        if (order.getSource().equals(OrderSource.EMPLOYEE)) {            couponInstanceService.writeOffCouponInstanceByOrderId(order);        }    }    private void postPaymentSuccess(Order order) throws Exception {        Store store = storeDao.findOne(order.getStoreId());        this.postPaymentSuccess(order, store);    }    @Override    public AllPayBaseResult queryMicroPay(String orderId) {        Order order = orderDao.findOne(orderId);        Store store = storeDao.findOne(order.getStoreId());        PayRequest payRequest = new PayRequest(PayTypeEnum.UNIFIED_TRADE_QUERY.getCode(),                store.getMchId(), orderId);        Map objectAsMap = objectMapper.convertValue(payRequest, Map.class);        payRequest.setUpSign(objectAsMap, store.getKey());        String requestXML = payRequest.toXML();        log.info("The request body of payment query is:{}", requestXML);        String xml = "";        try {            xml = OkHttpUtils.xmlPost(Payutils.ALI_QR_CODE, requestXML);        } catch (IOException e1) {            e1.printStackTrace();        }        log.info("The response body of payment query is:{}", xml);        return (AllPayBaseResult) xstream.fromXML(xml, new AllPayBaseResult());    }    private SwiftPassPaymentQueryBaseResult queryMicroPay(String outTradeNo, String mchId, String key) {        PayRequest payRequest = new PayRequest(PayTypeEnum.UNIFIED_TRADE_QUERY.getCode(),                mchId, outTradeNo);        Map objectAsMap = objectMapper.convertValue(payRequest, Map.class);        payRequest.setUpSign(objectAsMap, key);        String requestXML = payRequest.toXML();        log.info("The request body of payment query is:{}", requestXML);        String xml = restTemplate.postForEntity(Payutils.ALI_QR_CODE, requestXML, String.class).getBody();        log.info("The response body of payment query is:{}", xml);        return (SwiftPassPaymentQueryBaseResult) xstream.fromXML(xml, new SwiftPassPaymentQueryBaseResult());    }    @Override    public void callbackForMicroPaymentSuccess(SwiftPassPaymentQueryBaseResult queryResult) throws Exception {        redisSyncLocker.idLock(queryResult.getOutTradeNo(), (ISyncExecutor) o -> {            Order order = orderDao.findOne(queryResult.getOutTradeNo());            Reward reward = rewardDao.findOne(queryResult.getOutTradeNo());            if (reward != null) {                if (reward.getStatus().equals(OrderStatus.FINISHED) || reward.getStatus().equals(OrderStatus.UNFINISHED)) {                    // 已经处理过支付成功事件                    return null;                }                reward.setPaymentTime(MyDateUtils.getDateFormatDd(queryResult.getTimeEnd(), "yyyyMMddHHmmss"));                reward.setChannel(queryResult.getTradeType());                reward.setStatus(OrderStatus.FINISHED);                AccountBalance accountBalance = accountBalanceDao.findByStoreId(reward.getStoreId());                log.info("accountBalance" + accountBalance);                if (accountBalance == null) {                    accountBalance = new AccountBalance(queryResult.getTotalFee() / 100.0, reward.getStoreId());                } else {                    accountBalance.setAmount(accountBalance.getAmount() + queryResult.getTotalFee() / 100.0);                }                // 订单与支付信息的更新在同一个事务中                transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                    @Override                    protected void doInTransactionWithoutResult(TransactionStatus status) {                        rewardDao.save(reward);                    }                });                accountBalanceDao.save(accountBalance);                aliyunMNSSend.sendClint(reward.getId());            } else {                if (order.getStatus().equals(OrderStatus.FINISHED) || order.getStatus().equals(OrderStatus.UNFINISHED)) {                    // 已经处理过支付成功事件                    return null;                }                Store store = storeDao.findOne(order.getStoreId());                Payment payment = new Payment();                payment.setId(queryResult.getTransactionId());                payment.setOrderId(queryResult.getOutTradeNo());                payment.setStoreId(order.getStoreId());                payment.setSuccess(queryResult.isSuccess());                payment.setStatus(PaymentStatus.SUCCESS);                Date paymentTime = MyDateUtils.getDateFormatDd(queryResult.getTimeEnd(), "yyyyMMddHHmmss");                payment.setCreateTime(paymentTime);                payment.setAmount(queryResult.getTotalFee() / 100.0);                payment.setChannel(queryResult.getTradeType());                if (OrderSource.POS == order.getSource()) {                    order.setStatus(OrderStatus.FINISHED);                } else {                    order.setStatus(OrderStatus.UNFINISHED);                }                order.setPaymentTime(payment.getCreateTime());                order.setPayId(payment.getId());                order.setChannel(queryResult.getTradeType());                // 订单与支付信息的更新在同一个事务中                transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                    @Override                    protected void doInTransactionWithoutResult(TransactionStatus status) {                        paymentDao.save(payment);                        orderDao.save(order);                    }                });                postPaymentSuccess(order, store);            }            return null;        });    }    @Override    public void callbackForMicroPaymentFailed(String orderId, SwiftPassPaymentQueryBaseResult queryResult) throws Exception {        redisSyncLocker.idLock(orderId, o -> {            Order order = orderDao.findOne(orderId);            Reward reward = rewardDao.findOne(orderId);            if (reward != null) {                if (reward.getStatus().equals(OrderStatus.INIT)) {                    // 说明已经处理过支付失败的情况                    return null;                } else {                    // 支付失败后订单返回未结算状态，允许再次结算                    reward.setStatus(OrderStatus.INIT);                    transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                        @Override                        protected void doInTransactionWithoutResult(TransactionStatus status) {                            rewardDao.save(reward);                        }                    });                }            } else {                if (order.getStatus().equals(OrderStatus.CANCELED)) {                    // 说明已经处理过支付失败的情况                    return null;                } else {                    // 支付失败后订单返回未结算状态，允许再次结算                    order.setStatus(OrderStatus.CANCELED);                    transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                        @Override                        protected void doInTransactionWithoutResult(TransactionStatus status) {                            orderDao.save(order);                        }                    });                }            }            return null;        });    }    @Override    public void cashPay(String orderId, double amount, PaymentChannel channel) throws Exception {        redisSyncLocker.idLock(orderId, o -> {            Order order = orderDao.findOne(orderId);            if (order.getAmount() != amount) {                throw new AmountNotMatchException(order.getAmount(), amount);            }            log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "现金支付开始", "支付单" + order);            if (order.getStatus().equals(OrderStatus.UNFINISHED) || order.getStatus().equals(OrderStatus.FINISHED)) {                // 已支付                return null;            } else if (!order.getStatus().equals(OrderStatus.INIT)) {                // 订单当前状态不允许进行支付                throw new RuntimeException("支付失败，请返回重新点单！");            } else {                Payment payment = new Payment();                payment.setId(UuidUtil.getUuid());                payment.setChannel(channel.name());                payment.setAmount(amount);                payment.setCreateTime(new Date());                payment.setSuccess(true);                payment.setOrderId(orderId);                payment.setStoreId(order.getStoreId());                Store store = storeDao.findOne(order.getStoreId());                if (OrderSource.POS == order.getSource()) {                    order.setStatus(OrderStatus.FINISHED);                } else {                    order.setStatus(OrderStatus.UNFINISHED);                }                order.setPayId(payment.getId());                order.setPaymentTime(new Date());                order.setChannel(channel.name());                transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                    @Override                    protected void doInTransactionWithoutResult(TransactionStatus status) {                        paymentDao.save(payment);                        orderDao.save(order);                    }                });                postPaymentSuccess(order, store);                log.info("门店{}, 订单号{}, 操作{}, 操作内容{}", order.getStoreId(), order.getId(), "现金支付结束", "支付订单" + order);            }            return null;        });    }    @Override    public void memberPay(String orderId, double amount) throws Exception {        Order order = orderDao.findOne(orderId);        if (order.getAmount() != amount) {            throw new AmountNotMatchException(order.getAmount(), amount);        }        if (order.getStatus().equals(OrderStatus.UNFINISHED) || order.getStatus().equals(OrderStatus.FINISHED)) {            // 已支付            throw new RuntimeException("订单已支付完成，请勿重新进行支付");        } else if (!order.getStatus().equals(OrderStatus.INIT) && !order.getStatus().equals(OrderStatus.CANCELED)) {            // 订单当前状态不允许进行支付            throw new RuntimeException("订单当前状态不允许进行支付，请返回主页重新下单！");        } else {            TeamTransaction teamTransaction = teamTransactionDao.findByStoreIdAndEnable(order.getStoreId(), true);            MemberTeamAccount teamAccount = null;            BigDecimal paidDecimal = BigDecimal.valueOf(amount);            BigDecimal amountBefore;            BigDecimal bonusBefore;            BigDecimal bonusAfter;            BigDecimal amountAfter;            MemberAccount account = null;            if (teamTransaction != null) {                teamAccount = memberTeamAccountDao.findByMemberIdAndEnabledAndTeamId(order.getMemberId(), true, teamTransaction.getTeamId());                if (teamAccount != null) {                    if (teamAccount.getBonus() + teamAccount.getAmount() < amount) {                        throw new MemberAccountNotEnoughException(amount, teamAccount.getBonus() + teamAccount.getAmount());                    } else {                        amountBefore = BigDecimal.valueOf(teamAccount.getAmount());                        amountAfter = amountBefore.subtract(paidDecimal);                        bonusBefore = BigDecimal.valueOf(teamAccount.getBonus());                        bonusAfter = BigDecimal.valueOf(teamAccount.getBonus());                        if (amountAfter.compareTo(BigDecimal.ZERO) < 0) {                            bonusAfter = bonusBefore.add(amountAfter);                            amountAfter = BigDecimal.ZERO;                            teamAccount.setAmount(amountAfter.doubleValue());                            teamAccount.setBonus(bonusAfter.doubleValue());                            teamAccount.setLastConsumeTime(new Date());                        } else {                            teamAccount.setAmount(amountAfter.doubleValue());                        }                    }                } else {                    account = memberAccountDao.getStoreIdAndMemberId(order.getStoreId(), order.getMemberId());                    if (account.getTotalAmount() < amount) {                        throw new MemberAccountNotEnoughException(amount, account.getTotalAmount());                    }                    amountBefore = BigDecimal.valueOf(account.getAmount());                    bonusBefore = BigDecimal.valueOf(account.getBonus());                    bonusAfter = BigDecimal.valueOf(account.getBonus());                    // 会员余额消费先扣本金，再扣赠送金额                    amountAfter = amountBefore.subtract(paidDecimal);                    if (amountAfter.compareTo(BigDecimal.ZERO) < 0) {                        bonusAfter = bonusBefore.add(amountAfter);                        amountAfter = BigDecimal.ZERO;                        account.setAmount(amountAfter.doubleValue());                        account.setBonus(bonusAfter.doubleValue());                        account.setLastConsumeTime(new Date());                    } else {                        account.setAmount(amountAfter.doubleValue());                    }                }            } else {                account = memberAccountDao.getStoreIdAndMemberId(order.getStoreId(), order.getMemberId());                if (account.getTotalAmount() < amount) {                    throw new MemberAccountNotEnoughException(amount, account.getTotalAmount());                }                amountBefore = BigDecimal.valueOf(account.getAmount());                bonusBefore = BigDecimal.valueOf(account.getBonus());                bonusAfter = BigDecimal.valueOf(account.getBonus());                // 会员余额消费先扣本金，再扣赠送金额                amountAfter = amountBefore.subtract(paidDecimal);                if (amountAfter.compareTo(BigDecimal.ZERO) < 0) {                    bonusAfter = bonusBefore.add(amountAfter);                    amountAfter = BigDecimal.ZERO;                    account.setAmount(amountAfter.doubleValue());                    account.setBonus(bonusAfter.doubleValue());                    account.setLastConsumeTime(new Date());                } else {                    account.setAmount(amountAfter.doubleValue());                }            }            // 新建支付信息            Payment payment = new Payment();            payment.setSuccess(true);            payment.setId(UuidUtil.getUuid());            payment.setOrderId(order.getId());            payment.setAmount(amount);            payment.setChannel(PaymentChannel.MEMBER.name());            payment.setStatus(PaymentStatus.SUCCESS);            payment.setStoreId(order.getStoreId());            // 新建余额变动明细            MemberAccountTransaction tran = new MemberAccountTransaction();            tran.setStoreId(order.getStoreId());            tran.setOrderId(order.getId());            tran.setId(UuidUtil.getUuid());            tran.setMemberId(order.getMemberId());            tran.setType(MemberAccountTransactionType.WITHDRAW);            tran.setAmount(amountBefore.subtract(amountAfter).doubleValue());            if (teamTransaction != null) {                if (teamAccount != null) {                    tran.setAmountAfter(teamAccount.getAmount());                } else {                    tran.setAmountAfter(account.getAmount());                }            } else {                tran.setAmountAfter(account.getAmount());            }            tran.setAmountBefore(amountBefore.doubleValue());            tran.setBonus(bonusBefore.subtract(bonusAfter).doubleValue());            tran.setBonusBefore(bonusBefore.doubleValue());            tran.setBonusAfter(bonusAfter.doubleValue());            // 更新订单            if (OrderSource.POS == order.getSource()) {                order.setStatus(OrderStatus.FINISHED);            } else {                order.setStatus(OrderStatus.UNFINISHED);            }            order.setPaymentTime(new Date());            order.setChannel(PaymentChannel.MEMBER.name());            Member member = memberDao.findOne(order.getMemberId());            member.setAmount(member.getAmount() - order.getTotal());            member.setPoints(member.getPoints() + (int) order.getTotal());            transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                @Override                protected void doInTransactionWithoutResult(TransactionStatus status) {                    Payment savedPayment = paymentDao.save(payment);                    tran.setPaymentId(savedPayment.getId());                    memberAccountTransactionDao.save(tran);                    order.setPayId(savedPayment.getId());                    orderDao.save(order);                    memberDao.save(member);                }            });            if (teamTransaction != null) {                if (teamAccount != null) {                    memberTeamAccountDao.save(teamAccount);                } else {                    memberAccountDao.save(account);                }            } else {                memberAccountDao.save(account);            }            postPaymentSuccess(order);        }    }    @Override    public SwiftPassJSPayResult jsPay(String orderId, String openId) throws Exception {        return (SwiftPassJSPayResult) redisSyncLocker.idLock(orderId, o -> {            Order order = orderDao.findOne(orderId);            Store store = storeDao.findOne(order.getStoreId());            //初始化请求实体            PayRequest payRequest = new PayRequest(PayTypeEnum.PAY_WEIXIN_JSPAY.getCode(),                    //appid写死所有的均配置火星铺手的微信公众号                    store.getMchId(), orderId, getBody(order), openId, "wxf6f45bc02f8e7de8 ",/*"wxf6f45bc02f8e7de8",*/                    (int) (order.getAmount() * 100), "172.18.0.1", baseURL + "/v1/pay/callBack");            payRequest.setSign_agentno("10100000284");            payRequest.setUpSign(objectMapper.convertValue(payRequest, Map.class), store.getKey());            String requestBody = payRequest.toXML();            log.info("The request body of JSPAY is:{}", payRequest);            String xml = "";            try {                xml = OkHttpUtils.xmlPost(Payutils.ALI_QR_CODE, payRequest.toXML());            } catch (IOException e1) {                e1.printStackTrace();            }            log.info("The response body of JSPAY is:{}", xml);   /* String xml = restTemplate.postForEntity(Payutils.ALI_QR_CODE, requestBody, String.class).getBody();    log.info("The response body of JSPAY is:{}", xml);*/            SwiftPassJSPayResult result = (SwiftPassJSPayResult) xstream.fromXML(xml, new SwiftPassJSPayResult());            if (result.isSuccess()) {                // 更新订单状态到支付中，防止其被更新                transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                    @Override                    protected void doInTransactionWithoutResult(TransactionStatus status) {                        order.setStatus(OrderStatus.NOTSURE);                        orderDao.save(order);                    }                });            }            return result;        });    }    @Override    public SwiftPassQRCodePayResult qrCodePay(String orderId, PayTypeEnum type) throws Exception {        return (SwiftPassQRCodePayResult) redisSyncLocker.idLock(orderId, new ISyncExecutor() {            @Override            public Object execute(Object o) throws Exception {                Order order = orderDao.findOne(orderId);                Store store = storeDao.findOne(order.getStoreId());                //初始化请求实体                PayRequest payRequest = new PayRequest(type.getCode(), store.getMchId(),                        orderId, getBody(order),                        (int) Math.rint(order.getAmount() * 100), "172.17.0.1",                        baseURL + "/v1/pay/callBack");                payRequest.setService("unified.trade.native");                //这里是生成二维码的                payRequest.setUpSign(objectMapper.convertValue(payRequest, Map.class), store.getKey());                String requestBody = payRequest.toXML();                log.info("The request body of QR code payment is:{}", requestBody);                String xml = "";                try {                    xml = OkHttpUtils.xmlPost(Payutils.ALI_QR_CODE, payRequest.toXML());                } catch (IOException e1) {                    e1.printStackTrace();                }                log.info("The response XML of micro pay is:{}", xml);                SwiftPassQRCodePayResult result = (SwiftPassQRCodePayResult) xstream.fromXML(xml, new SwiftPassQRCodePayResult());                if (result.isSuccess()) {                    // 更新订单状态到支付中，防止其被更新                    transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                        @Override                        protected void doInTransactionWithoutResult(TransactionStatus status) {                            order.setStatus(OrderStatus.NOTSURE);                            orderDao.save(order);                        }                    });                }                return result;            }        });    }    @Override    public SwiftPassQRCodePayResult qrRewardCodePay(String rewardId, PayTypeEnum type) {        Reward reward = rewardDao.findOne(rewardId);        Store store = storeDao.findOne("574b59ef-b19c-11e7-9233-37891743d141");        //初始化请求实体        PayRequest payRequest = new PayRequest(type.getCode(), store.getMchId(),                rewardId, getRewardBody(reward),                (int) Math.rint(reward.getTotal() * 100), "172.17.0.1",                baseURL + "/v1/pay/callBack");        payRequest.setService("unified.trade.native");        //这里是生成二维码的        payRequest.setUpSign(objectMapper.convertValue(payRequest, Map.class), store.getKey());        // String requestBody = payRequest.toXML();        log.info("The request body of QR code payment is:{}", payRequest.toXML());        String xml = "";        try {            xml = OkHttpUtils.xmlPost(Payutils.ALI_QR_CODE, payRequest.toXML());        } catch (IOException e1) {            e1.printStackTrace();        }        /*  String xml = restTemplate.postForEntity(Payutils.ALI_QR_CODE, requestBody, String.class).getBody();*/        log.info("The response body of QR code payment is:{}", xml);        SwiftPassQRCodePayResult result = (SwiftPassQRCodePayResult) xstream.fromXML(xml, new SwiftPassQRCodePayResult());        if (result.isSuccess()) {            // 更新订单状态到支付中，防止其被更新            transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                @Override                protected void doInTransactionWithoutResult(TransactionStatus status) {                    reward.setStatus(OrderStatus.NOTSURE);                    rewardDao.save(reward);                }            });        }        return result;    }    @Override    public ALLPayQrCodeResult qrStockOrderCodePay(String orderId, PayTypeEnum type) {        StockOrder order = shopDao.findOne(orderId);        Store store = storeDao.findOne("574b59ef-b19c-11e7-9233-37891743d141");        //初始化请求实体        PayRequest payRequest = new PayRequest(type.getCode(), store.getMchId(),                orderId, getStockOrderBody(order),                (int) Math.rint(order.getAmount() * 100), "172.17.0.1",                baseURL + "/v1/pay/hs/stockCallBack");        payRequest.setService("unified.trade.native");        //这里是生成二维码的        payRequest.setUpSign(objectMapper.convertValue(payRequest, Map.class), store.getKey());        //  String requestBody = payRequest.toXML();        log.info("The request body of QR code payment is:{}", payRequest.toXML());        String xml = "";        try {            xml = OkHttpUtils.xmlPost(Payutils.ALI_QR_CODE, payRequest.toXML());        } catch (IOException e1) {            e1.printStackTrace();        }        log.info("The response XML of micro pay is:{}", xml);        /*   String xml = restTemplate.postForEntity(Payutils.ALI_QR_CODE, requestBody, String.class).getBody();*/        log.info("The response body of QR code payment is:{}", xml);        ALLPayQrCodeResult result = new ALLPayQrCodeResult();        BeanUtils.copyProperties(xstream.fromXML(xml, new SwiftPassQRCodePayResult()), result);        if (result.isSuccess()) {            // 更新订单状态到支付中，防止其被更新            transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                @Override                protected void doInTransactionWithoutResult(TransactionStatus status) {                    order.setStatus("PAY");                    shopDao.save(order);                }            });        }        return result;    }    @Override    public void handlePaymentNotify(String xml) throws Exception {        SwiftPassPaymentNotify notify = (SwiftPassPaymentNotify) xstream.fromXML(xml, new SwiftPassPaymentNotify());        String orderId = notify.getOutTradeNo();        redisSyncLocker.idLock(orderId, (ISyncExecutor) o -> {            String orgOrderId = orderId;            if (orderId.length() > 32) {                orgOrderId = orderId.substring(4);            }            Order order = orderDao.findByIdOrPayOrderIdAndAmountGreaterThan(orgOrderId, orderId, 0);            Reward reward = rewardDao.findOne(orderId);            if (reward != null) {                if (notify.isPaymentSuccess()) {                    if (reward.getStatus().equals(OrderStatus.FINISHED) || reward.getStatus().equals(OrderStatus.UNFINISHED)) {                        // 已经成功处理过该消息                        return null;                    } else {                        Date paymentTime = MyDateUtils.getDateFormatDd(notify.getTimeEnd(), "yyyyMMddHHmmss");                        reward.setChannel(notify.getTradeType());                        reward.setPaymentTime(paymentTime);                        reward.setStatus(OrderStatus.FINISHED);                        reward.setCommission(notify.getTotalFee() / 100.0);                        reward.setCompanyAmount(notify.getTotalFee() / 1000.0);                        AccountBalance accountBalance = accountBalanceDao.findByStoreId(reward.getStoreId());                        log.info("accountBalance" + accountBalance);                        if (accountBalance == null) {                            accountBalance = new AccountBalance(notify.getTotalFee() / 100.0, reward.getStoreId());                        } else {                            accountBalance.setAmount(accountBalance.getAmount() + notify.getTotalFee() / 100.0);                        }                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                rewardDao.save(reward);                            }                        });                        accountBalanceDao.save(accountBalance);                        notifyRewardNewCallService(reward, "handlePaymentNotify:" + orderId);                    }                }            } else {                if (notify.isPaymentSuccess()) {                    if (order.getStatus().equals(OrderStatus.FINISHED) || order.getStatus().equals(OrderStatus.UNFINISHED)) {                        // 已经成功处理过该消息                        return null;                    } else {                        Date paymentTime = MyDateUtils.getDateFormatDd(notify.getTimeEnd(), "yyyyMMddHHmmss");                        Payment payment = new Payment();                        payment.setId(notify.getTransactionId());                        payment.setChannel(notify.getTradeType());                        payment.setAmount(notify.getTotalFee() / 100.0);                        payment.setCreateTime(paymentTime);                        payment.setOrderId(order.getId());                        payment.setStatus(PaymentStatus.SUCCESS);                        payment.setStoreId(order.getStoreId());                        payment.setSuccess(true);                        // 更新订单                        order.setPayId(notify.getTransactionId());                        order.setPaymentTime(paymentTime);                        order.setChannel(notify.getTradeType());                        if (OrderSource.POS == order.getSource()) {                            order.setStatus(OrderStatus.FINISHED);                        } else {                            order.setStatus(OrderStatus.UNFINISHED);                        }                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                paymentDao.save(payment);                                orderDao.save(order);                            }                        });                        postPaymentSuccess(order);                    }                } else {                    if (order.getStatus().equals(OrderStatus.INIT)) {                        // 已经成功处理过该消息                        return null;                    } else {                        order.setStatus(OrderStatus.CANCELED);                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                orderDao.save(order);                            }                        });                    }                }            }            return null;        });    }    @Override    public Map saoBeiPaymentNotify(SaoBeiCallBackReq req) throws Exception {        Map map = new HashMap();        String orderId = req.getTerminal_trace();        redisSyncLocker.idLock(orderId, (ISyncExecutor) o -> {            Order order = orderDao.findOne(orderId);            Reward reward = rewardDao.findOne(orderId);            if (reward != null) {                if (req.getResult_code().equals("01")) {                    if (reward.getStatus().equals(OrderStatus.FINISHED) || reward.getStatus().equals(OrderStatus.UNFINISHED)) {                        // 已经成功处理过该消息                        return null;                    } else {                        Date paymentTime = MyDateUtils.getDateFormatDd(req.getTerminal_time(), "yyyyMMddHHmmss");                        reward.setChannel(dealPayType(req.getPay_type()));                        reward.setPaymentTime(paymentTime);                        reward.setStatus(OrderStatus.FINISHED);                        reward.setCommission(Integer.valueOf(req.getTotal_fee()) / 100.0);                        reward.setCompanyAmount(Integer.valueOf(req.getTotal_fee()) / 1000.0);                        AccountBalance accountBalance = accountBalanceDao.findByStoreId(reward.getStoreId());                        log.info("accountBalance" + accountBalance);                        if (accountBalance == null) {                            accountBalance = new AccountBalance(Integer.valueOf(req.getTotal_fee()) / 100.0, reward.getStoreId());                        } else {                            accountBalance.setAmount(accountBalance.getAmount() + Integer.valueOf(req.getTotal_fee()) / 100.0);                        }                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                rewardDao.save(reward);                            }                        });                        accountBalanceDao.save(accountBalance);                        notifyRewardNewCallService(reward, "saoBeiPaymentNotify:" + orderId);                    }                    map.put("return_code", "01");                    map.put("return_msg", "SUCCESS");                }            } else {                if (req.getResult_code().equals("01")) {                    if (order.getStatus().equals(OrderStatus.FINISHED) || order.getStatus().equals(OrderStatus.UNFINISHED)) {                        // 已经成功处理过该消息                        return null;                    } else {                        Date paymentTime = MyDateUtils.getDateFormatDd(req.getTerminal_time(), "yyyyMMddHHmmss");                        Payment payment = new Payment();                        payment.setId(UuidUtil.getUuid());                        payment.setChannel(dealPayType(req.getPay_type()));                        payment.setAmount(Integer.valueOf(req.getTotal_fee()) / 100.0);                        payment.setCreateTime(paymentTime);                        payment.setOrderId(order.getId());                        payment.setStatus(PaymentStatus.SUCCESS);                        payment.setStoreId(order.getStoreId());                        payment.setSuccess(true);                        // 更新订单                        order.setPayChannel(OrderPayChannel.SAO_BEI);                        order.setPayId(payment.getId());                        order.setPaymentTime(paymentTime);                        order.setChannel(dealPayType(req.getPay_type()));                        if (OrderSource.POS == order.getSource()) {                            order.setStatus(OrderStatus.FINISHED);                        } else {                            order.setStatus(OrderStatus.UNFINISHED);                        }                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                paymentDao.save(payment);                                orderDao.save(order);                            }                        });                        postPaymentSuccess(order);                    }                    map.put("return_code", "01");                    map.put("return_msg", "SUCCESS");                } else {                    if (order.getStatus().equals(OrderStatus.INIT)) {                        // 已经成功处理过该消息                        return null;                    } else {                        order.setStatus(OrderStatus.CANCELED);                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                orderDao.save(order);                            }                        });                    }                }            }            return null;        });        return map;    }    @Override    public String huifuPaymentNotify(HuiFuCallBackReq req) throws Exception {        String s = "RECV_ORD_ID_" + req.getOrdId();        String orderId = req.getMerOrdId();        redisSyncLocker.idLock(orderId, (ISyncExecutor) o -> {            Order order = orderDao.findOne(orderId);            Reward reward = rewardDao.findOne(orderId);            if (reward != null) {                if (req.getTransStat().equals("S")) {                    if (reward.getStatus().equals(OrderStatus.FINISHED) || reward.getStatus().equals(OrderStatus.UNFINISHED)) {                        // 已经成功处理过该消息                        return null;                    } else {                        Date paymentTime = MyDateUtils.getDateFormatDd(req.getTransDate() + req.getTransTime(), "yyyyMMddHHmmss");                        reward.setChannel(dealHuifuPayType(req.getPayTypeDetail()));                        reward.setPaymentTime(paymentTime);                        reward.setStatus(OrderStatus.FINISHED);                        reward.setCommission(Integer.valueOf(req.getOrdAmt()) / 100.0);                        reward.setCompanyAmount(Integer.valueOf(req.getOrdAmt()) / 1000.0);                        AccountBalance accountBalance = accountBalanceDao.findByStoreId(reward.getStoreId());                        log.info("accountBalance" + accountBalance);                        if (accountBalance == null) {                            accountBalance = new AccountBalance(Integer.valueOf(req.getOrdAmt()) / 100.0, reward.getStoreId());                        } else {                            accountBalance.setAmount(accountBalance.getAmount() + Integer.valueOf(req.getOrdAmt()) / 100.0);                        }                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                rewardDao.save(reward);                            }                        });                        accountBalanceDao.save(accountBalance);                        notifyRewardNewCallService(reward, "huifuPaymentNotify:" + orderId);                    }                }            } else {                if (req.getTransStat().equals("S")) {                    if (order.getStatus().equals(OrderStatus.FINISHED) || order.getStatus().equals(OrderStatus.UNFINISHED)) {                        // 已经成功处理过该消息                        return null;                    } else {                        Date paymentTime = MyDateUtils.getDateFormatDd(req.getTransDate() + req.getTransTime(), "yyyyMMddHHmmss");                        Payment payment = new Payment();                        payment.setId(UuidUtil.getUuid());                        payment.setChannel(dealHuifuPayType(req.getPayTypeDetail()));                        payment.setAmount(Integer.valueOf(req.getOrdAmt()) / 100.0);                        payment.setCreateTime(paymentTime);                        payment.setOrderId(order.getId());                        payment.setStatus(PaymentStatus.SUCCESS);                        payment.setStoreId(order.getStoreId());                        payment.setSuccess(true);                        // 更新订单                        order.setPayChannel(OrderPayChannel.SAO_BEI);                        order.setPayId(payment.getId());                        order.setPaymentTime(paymentTime);                        order.setChannel(dealHuifuPayType(req.getPayTypeDetail()));                        if (OrderSource.POS == order.getSource()) {                            order.setStatus(OrderStatus.FINISHED);                        } else {                            order.setStatus(OrderStatus.UNFINISHED);                        }                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                paymentDao.save(payment);                                orderDao.save(order);                            }                        });                        postPaymentSuccess(order);                    }                } else {                    if (order.getStatus().equals(OrderStatus.INIT)) {                        // 已经成功处理过该消息                        return null;                    } else {                        order.setStatus(OrderStatus.CANCELED);                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                orderDao.save(order);                            }                        });                    }                }            }            return null;        });        return s;    }    @Override    public String suixinfuPaymentNotify(SuiXinFuCallBackRes req) throws Exception {        String orderId = req.getOrdNo();        if (req.getBizMsg().contains("不能重复")) {            return "订单号不能重复";        }        String orgOrderId = orderId;        if (orderId.length() > 32) {            orgOrderId = orderId.substring(4);        }        String finalOrgOrderId = orgOrderId;        redisSyncLocker.idLock(orgOrderId, (ISyncExecutor) o -> {            int getAmount = (int) (Double.valueOf(req.getAmt()) * 100);            Order order = orderDao.findByIdOrPayOrderIdAndAmountGreaterThan(finalOrgOrderId, orderId, 0);            Reward reward = rewardDao.findOne(orderId);            if (reward != null) {                if (req.getBizCode().equals("0000")) {                    if (reward.getStatus().equals(OrderStatus.FINISHED) || reward.getStatus().equals(OrderStatus.UNFINISHED)) {                        // 已经成功处理过该消息                        return null;                    } else {                        Date paymentTime = MyDateUtils.getDateFormatDd(req.getPayTime(), "yyyyMMddHHmmss");                        reward.setChannel(dealSuixinfuPayType(req.getPayType()));                        reward.setPaymentTime(paymentTime);                        reward.setStatus(OrderStatus.FINISHED);                        reward.setCommission(getAmount / 100.0);                        reward.setCompanyAmount(getAmount / 1000.0);                        AccountBalance accountBalance = accountBalanceDao.findByStoreId(reward.getStoreId());                        log.info("accountBalance" + accountBalance);                        if (accountBalance == null) {                            accountBalance = new AccountBalance(getAmount / 100.0, reward.getStoreId());                        } else {                            accountBalance.setAmount(accountBalance.getAmount() + getAmount / 100.0);                        }                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                rewardDao.save(reward);                            }                        });                        accountBalanceDao.save(accountBalance);                        notifyRewardNewCallService(reward, "suixinfuPaymentNotify:" + orderId);                    }                }            } else {                if (req.getBizCode().equals("0000")) {                    if (order.getStatus().equals(OrderStatus.FINISHED) || order.getStatus().equals(OrderStatus.UNFINISHED)) {                        // 已经成功处理过该消息                        return null;                    } else {                        Date paymentTime = MyDateUtils.getDateFormatDd(req.getPayTime(), "yyyyMMddHHmmss");                        Payment payment = new Payment();                        payment.setId(UuidUtil.getUuid());                        payment.setChannel(dealSuixinfuPayType(req.getPayType()));                        payment.setAmount(getAmount / 100.0);                        payment.setCreateTime(paymentTime);                        payment.setOrderId(order.getId());                        payment.setStatus(PaymentStatus.SUCCESS);                        payment.setStoreId(order.getStoreId());                        payment.setSuccess(true);                        // 更新订单                        order.setPayChannel(OrderPayChannel.SUI_XIN_FU);                        order.setPayId(payment.getId());                        order.setPaymentTime(paymentTime);                        order.setChannel(dealSuixinfuPayType(req.getPayType()));                        if (OrderSource.POS == order.getSource()) {                            order.setStatus(OrderStatus.FINISHED);                        } else {                            order.setStatus(OrderStatus.UNFINISHED);                        }                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                paymentDao.save(payment);                                orderDao.save(order);                            }                        });                        couponInstanceService.writeOffCouponInstanceByOrderId(order);                        postPaymentSuccess(order);                    }                } else {                    if (order.getStatus().equals(OrderStatus.INIT)) {                        // 已经成功处理过该消息                        return null;                    } else {                        order.setStatus(OrderStatus.CANCELED);                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus status) {                                orderDao.save(order);                            }                        });                    }                }            }            return null;        });        return req.getBizMsg();    }    @Override    public String suixinfuPaymentNotifyFrozen(SuiXinFuCallBackRes req) throws Exception {            LeaseProductOrder reward = leaseProductOrderDao.findByOrderNum(req.getOrdNo());            if (reward != null) {                redisSyncLocker.idLock(reward.getProductId() + "leaseLock", o -> {                    if (req.getBizCode().equals("0000")) {                        if (reward.getStatus().equals(OrderStatus.FINISHED) || reward.getStatus().equals(OrderStatus.UNFINISHED)) {                            // 已经成功处理过该消息                            return null;                        } else {                            LeaseProduct leaseProduct = leaseProductDao.findOne(reward.getProductId());                            boolean inventory = suiXinFuService.dealLeaseProductInventory(leaseProduct, reward.getNumName(), reward);                            if (inventory) {                                Date paymentTime = MyDateUtils.getDateFormatDd(req.getPayTime(), "yyyyMMddHHmmss");                                reward.setChannel(dealSuixinfuPayType(req.getPayType()));                                reward.setPayTime(paymentTime);                                log.info("店铺id{},消息通知时间{},订单状态{}", reward.getStoreId(), new Date(), reward);                                if (!reward.getSource().equals(OrderSource.POS)) {                                    notifyPOSNewOrderArrivalLease(reward);                                    log.info("店铺id{},消息通知时间并且进来{},订单状态{}", reward.getStoreId(), new Date(), reward);                                    reward.setStatus(OrderStatus.UNFINISHED);                                } else {                                    reward.setStatus(OrderStatus.FINISHED);                                }                            }                            log.info("门店{}, 订单号{},判断结果{}", reward.getStoreId(), reward.getOrderNum(), inventory);                            leaseProductOrderDao.save(reward);                        }                    }                    return null;                });            }        return req.getBizMsg();    }    private String dealPayType(String type) {        String payType = "";        switch (type) {            case "010":                payType = "pay.wechat.native";                break;            case "020":                payType = "pay.alipay.native";                break;            case "060":                payType = "pay.qq.micropay";                break;            case "080":                payType = "pay.jdpay.micropay";                break;            case "100":                payType = "pay.bestpay.micropay";                break;            case "110":                payType = "pay.unionpay.micropay";                break;        }        return payType;    }    private String dealSuixinfuPayType(String type) {        String payType = "";        switch (type) {            case "WECHAT":                payType = "pay.wechat.native";                break;            case "ALIPAY":                payType = "pay.alipay.native";                break;            case "UNIONPAY":                payType = "pay.unionpay.micropay";                break;        }        return payType;    }    private String dealHuifuPayType(String type) {        String payType = "";        switch (type) {            case "1010":                payType = "pay.alipay.native";                break;            case "1011":                payType = "pay.alipay.micropay";                break;            case "1020":                payType = "pay.weixin.native";                break;            case "1021":                payType = "pay.weixin.micropay";                break;            case "1024":                payType = "pay.weixin.jspay";                break;            case "1031":                payType = "pay.unionpay.micropay";                break;        }        return payType;    }    @Override    public void handleSxfStockNotify(SuiXinFuCallBackRes res) {        StockOrder stockOrder = shopDao.findOne(res.getOrdNo());        if (res.getBizCode().equals("0000")) {            if (stockOrder != null) {                Date paymentTime = MyDateUtils.getDateFormatDd(res.getPayTime(), "yyyyMMddHHmmss");                stockOrder.setPayEnabled(true);                stockOrder.setPayTime(paymentTime);                stockOrder.setChannel(dealSuixinfuPayType(res.getPayType()));                stockOrder.setStatus("PAY");                shopDao.save(stockOrder);            }        }    }    @Override    public void handleHsStockNotify(String xml) {        SwiftPassPaymentNotify notify = (SwiftPassPaymentNotify) xstream.fromXML(xml, new SwiftPassPaymentNotify());        StockOrder stockOrder = shopDao.findOne(notify.getOutTradeNo());        if (notify.isPaymentSuccess()) {            if (stockOrder != null) {                Date paymentTime = MyDateUtils.getDateFormatDd(notify.getTimeEnd(), "yyyyMMddHHmmss");                stockOrder.setPayEnabled(true);                stockOrder.setPayTime(paymentTime);                stockOrder.setChannel(notify.getTradeType());                shopDao.save(stockOrder);            }        }    }    @Override    public Payment refund(String orderId, String reason, String username) throws Exception {        return (Payment) redisSyncLocker.idLock(orderId, new ISyncExecutor() {            @Override            public Object execute(Object o) throws Exception {                Order order = orderDao.findOne(orderId);                Order getRefundOrder = orderDao.findByStoreIdAndRefOrderId(order.getStoreId(), order.getId());                order.setRefundReason(reason);                if (!order.getStatus().equals(OrderStatus.FINISHED)                        && !order.getStatus().equals(OrderStatus.UNFINISHED)) {                    throw new RuntimeException("订单未结算，不允许进行退款操作");                }                if (order.getType().equals(OrderType.MEMBER_DEPOSIT)) {                    throw new RuntimeException("会员充值不允许退单");                }                if (null != getRefundOrder) {                    throw new RuntimeException("该订单已退，请不要重复操作！");                }                CouponInstance couponInstance = couponInstanceDao.findByOrderId(order.getId());                if (couponInstance != null) {                    couponInstance.setStauts(CouponInstanceStatus.NORMAL);                    couponInstance.setValidateTime(null);                    couponInstance.setOrderId(null);                    couponInstanceDao.save(couponInstance);                }                StorePay storePay = storePayDao.findByStoreIdAndStartEnabled(order.getStoreId(), true);                List<Payment> payments = paymentDao.findByOrderIdAndSuccess(orderId, true);                SwiftPassRefundResult result = null;                for (Payment payment : payments) {                    if (!payment.isSuccess()) {                        // 忽略未成功的支付                        continue;                    }                    String id = UuidUtil.getUuid();                    log.info("payment.getChannel().equals(PaymentChannel.MEMBER.name())" + payment.getChannel().equals(PaymentChannel.MEMBER.name()));                    if (payment.isThirdParty()) {                        switch (storePay.getChannel()) {                            case SAO_BEI:                                result = saoBeiService.saoBeiRefund(order, storePay);                                break;                            case HUI_SHANG:                                result = hsService.refundPay(order, payment, storePay);                                break;                            case JL:                                result = null;                                break;                            case HUI_FU:                                result = huiFuService.huifuRefund(order, storePay);                                break;                            case SUI_XIN_FU:                                result = suiXinFuService.suixinfuRefund(id, order, storePay);                        }                        if (result.isSuccess()) {                            // 退款发起成功即认为退款成功                            Payment refundPayment = new Payment();                            BeanUtils.copyProperties(payment, refundPayment);                            // 中信返回的退款金额是正数                            refundPayment.setAmount(result.getRefundFee() / 100.0 * -1);                            refundPayment.setId(result.getRefundId());                            refundPayment.setStatus(PaymentStatus.SUCCESS);                            refundPayment.setCreateTime(new Date());                            //生成负订单记录                            Order refundOrder = GetNegativeOrder(order);                            order.setRefundTime(new Date());                            refundOrder.setId(id);                            refundOrder.setPaymentTime(new Date());                            refundOrder.setRefundTime(order.getRefundTime());                            transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                                @Override                                protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {                                    refundPayment.setOrderId(refundOrder.getId());                                    paymentDao.save(refundPayment);                                    orderDao.save(refundOrder);                                    orderDao.save(order);                                }                            });                            postRefundSuccess(order);                            return refundPayment;                        } else {                            throw new RuntimeException(result.getErrMsg());                        }                    } else if (payment.getChannel().equals(PaymentChannel.COUPON.name())) {                        // 老数据，认为优惠券是一种支付方式                        continue;                    } else if (payment.getChannel().equals(PaymentChannel.MEMBER.name())) {                        // 会员支付，创建一个反向支付冲抵                        Payment refundPayment = new Payment();                        BeanUtils.copyProperties(payment, refundPayment);                        refundPayment.setId(UuidUtil.getUuid());                        refundPayment.setCreateTime(new Date());                        refundPayment.setSuccess(true);                        refundPayment.setAmount(0 - payment.getAmount());                        BigDecimal beforeAmount;                        BigDecimal beforeBonus;                        BigDecimal afterAmount;                        BigDecimal afterBonus;                        TeamTransaction teamTransaction = teamTransactionDao.findByStoreIdAndEnable(order.getStoreId(), true);                        MemberAccount account = null;                        MemberAccountTransaction orgTrans = memberAccountTransactionDao.findOneByPaymentId(payment.getId());                        MemberTeamAccount teamAccount = null;                        if (teamTransaction != null) {                            teamAccount = memberTeamAccountDao.findByMemberIdAndEnabledAndTeamId(order.getMemberId(), true, teamTransaction.getTeamId());                            if (teamAccount != null) {                                beforeAmount = BigDecimal.valueOf(teamAccount.getAmount());                                beforeBonus = BigDecimal.valueOf(teamAccount.getBonus());                                afterAmount = beforeAmount.add(BigDecimal.valueOf(orgTrans.getAmount()));                                afterBonus = beforeBonus.add(BigDecimal.valueOf(orgTrans.getBonus()));                                teamAccount.setAmount(afterAmount.doubleValue());                                teamAccount.setBonus(afterBonus.doubleValue());                                teamAccount.setPoints(teamAccount.getPoints() - orgTrans.getAmount());                            } else {                                account = memberAccountDao.getStoreIdAndMemberId(order.getStoreId(), order.getMemberId());                                beforeAmount = BigDecimal.valueOf(account.getAmount());                                beforeBonus = BigDecimal.valueOf(account.getBonus());                                afterAmount = beforeAmount.add(BigDecimal.valueOf(orgTrans.getAmount()));                                afterBonus = beforeBonus.add(BigDecimal.valueOf(orgTrans.getBonus()));                                account.setAmount(afterAmount.doubleValue());                                account.setBonus(afterBonus.doubleValue());                            }                        } else {                            account = memberAccountDao.getStoreIdAndMemberId(order.getStoreId(), order.getMemberId());                            beforeAmount = BigDecimal.valueOf(account.getAmount());                            beforeBonus = BigDecimal.valueOf(account.getBonus());                            afterAmount = beforeAmount.add(BigDecimal.valueOf(orgTrans.getAmount()));                            afterBonus = beforeBonus.add(BigDecimal.valueOf(orgTrans.getBonus()));                            account.setAmount(afterAmount.doubleValue());                            account.setBonus(afterBonus.doubleValue());                        }                        // 生成会员账户变动明细记录                        MemberAccountTransaction newTrans = new MemberAccountTransaction();                        newTrans.setAmount(0 - orgTrans.getAmount());                        newTrans.setAmountAfter(afterAmount.doubleValue());                        newTrans.setBonus(0 - orgTrans.getBonus());                        newTrans.setBonusBefore(beforeBonus.doubleValue());                        newTrans.setBonusAfter(afterBonus.doubleValue());                        newTrans.setType(MemberAccountTransactionType.REFUND);                        newTrans.setMemberId(orgTrans.getMemberId());                        newTrans.setStoreId(orgTrans.getStoreId());                        //回滚会员总金额记录                        Member member = memberDao.findOne(order.getMemberId());                        member.setAmount(order.getAmount() + member.getAmount());                        member.setPoints(member.getPoints() - (int) order.getAmount());                        //生成负订单记录                        Order refundOrder = GetNegativeOrder(order);                        order.setRefundTime(new Date());                        refundOrder.setPaymentTime(new Date());                        refundOrder.setRefundTime(order.getRefundTime());                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {                                orderDao.save(order);                                Order savedOrder = orderDao.save(refundOrder);                                refundPayment.setOrderId(savedOrder.getId());                                Payment savedPayment = paymentDao.save(refundPayment);                                newTrans.setOrderId(savedOrder.getId());                                newTrans.setPaymentId(savedPayment.getId());                                newTrans.setId(UuidUtil.getUuid());                                memberAccountTransactionDao.save(newTrans);                                memberDao.save(member);                            }                        });                        if (teamTransaction != null) {                            if (teamAccount != null) {                                memberTeamAccountDao.save(teamAccount);                            } else {                                memberAccountDao.save(account);                            }                        } else {                            memberAccountDao.save(account);                        }                        postRefundSuccess(order);                        return refundPayment;                    } else {                        // 现金支付，收款码支付等线下支付方式                        // 创建一个反向支付冲抵                        Payment refundPayment = new Payment();                        BeanUtils.copyProperties(payment, refundPayment);                        refundPayment.setId(UuidUtil.getUuid());                        refundPayment.setCreateTime(new Date());                        refundPayment.setSuccess(true);                        refundPayment.setAmount(0 - payment.getAmount());                        //生成负订单记录                        Order refundOrder = GetNegativeOrder(order);                        order.setRefundTime(new Date());                        refundOrder.setPaymentTime(new Date());                        refundOrder.setRefundTime(order.getRefundTime());                        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                            @Override                            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {                                orderDao.save(order);                                orderDao.save(refundOrder);                                refundPayment.setOrderId(refundOrder.getId());                                paymentDao.save(refundPayment);                            }                        });                        postRefundSuccess(order);                        return refundPayment;                    }                }                throw new RuntimeException("该订单没有支付信息，退款失败");            }        });    }    @Override    public SwiftPassRefundQueryResult queryRefundResult(String refundOrderId) {        Order order = orderDao.findOne(refundOrderId);        Store store = storeDao.findOne(order.getStoreId());        PayRequest payRequest = new PayRequest(PayTypeEnum.UNIFIED_TRADE_REFUNDQUERY.getCode(), store.getMchId(), order);        payRequest.setUpSign(objectMapper.convertValue(payRequest, Map.class), store.getKey());        String requestBody = payRequest.toXML();        log.info("The request body of refund query is:{}", requestBody);        String xml = restTemplate.postForEntity(Payutils.ALI_QR_CODE, requestBody, String.class).getBody();        log.info("The response body of refund query is:{}", xml);        return (SwiftPassRefundQueryResult) xstream.fromXML(xml, new SwiftPassRefundQueryResult());    }    @Override    public void callbackForThirdPartyRefundSuccess(SwiftPassRefundQueryResult result) {        log.debug("Step in callback for third party refund success...");        Payment payment = paymentDao.findOne(result.getRefundId());        payment.setStatus(PaymentStatus.SUCCESS);        payment.setSuccess(true);        Date paymentTime = MyDateUtils.getDateFormatDd(result.getRefundTime(), "yyyyMMddHHmmss");        payment.setCreateTime(paymentTime);        Order refundOrder = orderDao.findOne(payment.getOrderId());        refundOrder.setStatus(OrderStatus.REFUNDED);        refundOrder.setPaymentTime(paymentTime);        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {            @Override            protected void doInTransactionWithoutResult(TransactionStatus status) {                orderDao.save(refundOrder);                paymentDao.save(payment);            }        });        try {            postRefundSuccess(refundOrder);        } catch (Exception e1) {            log.info(e1.toString());        }    }    @Override    public void callbackForThirdPartyRefundFail(SwiftPassRefundQueryResult result) {        Order refundOrder = orderDao.findOne(result.getOutRefundNo());        refundOrder.setStatus(OrderStatus.INIT);        transactoinTemplate.execute(new TransactionCallbackWithoutResult() {            @Override            protected void doInTransactionWithoutResult(TransactionStatus status) {                orderDao.save(refundOrder);            }        });    }    @Override    public void fillPaymentChannel() {        /*int index = 0;        for (int i = 0; i < 100; i++) {            log.info("Processing order payment channel fill request at index:{}", index);            Collection<? extends Order> orders = orderDao.findTop1000ByChannelIsNullAndStatusInOrderByUpdateTimeDesc(Arrays.asList(OrderStatus.FINISHED, OrderStatus.UNFINISHED));            if (null == orders || orders.size() == 0) {                break;            } else {                final Integer batch = index;                transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                    @Override                    protected void doInTransactionWithoutResult(TransactionStatus status) {                        for (Order order : orders) {                            log.info("Processing order:{} at batch:{}", order.getId(), batch);                            if (StringUtils.isEmpty(order.getPayId())) {                                log.warn("No pay id found in a settled order:{}", order.getId());                                order.setChannel("UNKNOWN");                                orderDao.save(order);                                continue;                            }                            Payment payment = paymentDao.findOne(order.getPayId());                            if (null == payment) {                                log.warn("No payment found by id:{}", order.getPayId());                                order.setChannel("UNKNOWN");                                orderDao.save(order);                                continue;                            }                            if (payment.getChannel().equalsIgnoreCase(PaymentChannel.ALIPAY.name()) || payment.getChannel().equalsIgnoreCase(PaymentChannel.WECHATPAY.name())) {                                SwiftPassPaymentQueryBaseResult result = queryMicroPay(order.getId());                                if (result.isSuccess()) {                                    order.setChannel(result.getTradeType());                                } else {                                    Store store = storeDao.findOne(order.getStoreId());                                    result = queryMicroPay(payment.getId(), store.getMchId(), store.getKey());                                    if (result.isSuccess()) {                                        order.setChannel(result.getTradeType());                                    } else {                                        order.setChannel("UNKNOWN");                                    }                                }                            } else {                                order.setChannel(payment.getChannel());                            }                            orderDao.save(order);                        }                    }                });                index += orders.size();            }        }        log.info("Fill payment channel finished");*/    }    @Override    public SwiftPassQRCodePayResult qrCallServiceCodePay(String id, PayTypeEnum type) {        CallTran callTran = callTranDao.findOne(id);        Store store = storeDao.findOne("574b59ef-b19c-11e7-9233-37891743d141");        //初始化请求实体        PayRequest payRequest = new PayRequest(type.getCode(), store.getMchId(),                callTran.getId(), getCallTranBody(callTran),                (int) Math.rint(callTran.getAmount() * 100), "172.17.0.1",                baseURL + "/v1/call/tran/callBack");        payRequest.setService("unified.trade.native");        //这里是生成二维码的        payRequest.setUpSign(objectMapper.convertValue(payRequest, Map.class), store.getKey());        //  String requestBody = payRequest.toXML();        log.info("The request body of QR code payment is:{}", payRequest.toXML());        String xml = "";        try {            xml = OkHttpUtils.xmlPost(Payutils.ALI_QR_CODE, payRequest.toXML());        } catch (IOException e1) {            e1.printStackTrace();        }        SwiftPassQRCodePayResult result = (SwiftPassQRCodePayResult) xstream.fromXML(xml, new SwiftPassQRCodePayResult());        if (result.isSuccess()) {            // 更新订单状态到支付中，防止其被更新            transactoinTemplate.execute(new TransactionCallbackWithoutResult() {                @Override                protected void doInTransactionWithoutResult(TransactionStatus status) {                    callTran.setStatus(OrderStatus.NOTSURE);                    callTranDao.save(callTran);                }            });        }        return result;    }    public void postRefundSuccess(Order order) throws Exception {        stockTransactionService.refundStockIn(order);        wechatTemplateService.refundOrder(order);    }    private void notifyPOSNewOrderArrival(Order order) {        try {            Map<String, String> map = new HashMap<>();            map.put("orderId", order.getId());            map.put("storeId", order.getStoreId());            map.put("type", "ORDER");            putWs(map);        } catch (Exception e) {            log.warn("Fail to send websocket notify to store:{}", order.getStoreId());        }    }    private void notifyPOSNewOrderArrivalLease(LeaseProductOrder order) {        try {            Map<String, String> map = new HashMap<>();            map.put("orderId", order.getId() + "");            map.put("storeId", order.getStoreId());            map.put("type", "LEASE");            putWs(map);        } catch (Exception e) {            log.warn("Fail to send websocket notify to store:{}", order.getStoreId());        }    }    private void notifyMakeTypeNewOrderArrival(String storeId) {        try {            Map<String, String> map = new HashMap<>();            map.put("storeId", storeId);            map.put("type", "MAKE");            putWs(map);        } catch (Exception e) {            log.warn("Fail to send websocket notify to store:{}", storeId);        }    }    private void putWs(Map<String, String> map) {        try {            //发送ws            String url = urlUtils.getWs();            OkHttpUtils.post(url, com.alibaba.fastjson.JSONObject.toJSONString(map));        } catch (Exception ex) {            log.error(" Invitation code initialization failed msg:{}", ex);        }    }    private SwiftPassMicroPayBaseResult micropay(Order order, String authCode, String mchId, String mchKey) {        //初始化请求实体        PayRequest payRequest = new PayRequest(PayTypeEnum.UNIFIED_TRADE_MICROPAY.getCode(), mchId,                order.getId(), getBody(order),                (int) Math.rint(order.getAmount() * 100), "172.17.0.1",                "");        payRequest.setAuth_code(authCode);        // QQ钱包刷卡需要该字段        payRequest.setDevice_info("iPhoneX");        payRequest.setSign_agentno("10100000284");        ObjectMapper objectMapper = new ObjectMapper();        payRequest.setUpSign(objectMapper.convertValue(payRequest, Map.class), "h92Tz0wF6QX66hR4pM7VVdXD4NNS3cSO");       /* Map objectAsMap = objectMapper.convertValue(payRequest, Map.class);        payRequest.setUpSign(objectAsMap, mchKey);*/        log.info("The request XML of micro pay is:{}", payRequest.toXML());        try {           /* RestTemplate rest = new RestTemplate();            String xml = rest.postForEntity(Payutils.ALI_QR_CODE, payRequest.toXML(), String.class).getBody();*/            String xml = "";            try {                xml = OkHttpUtils.xmlPost(Payutils.ALI_QR_CODE, payRequest.toXML());            } catch (IOException e1) {                e1.printStackTrace();            }            log.info("The response XML of micro pay is:{}", xml);            String str = null;            try {                str = new String(xml.getBytes("iso8859-1"), "UTF-8");            } catch (UnsupportedEncodingException e1) {                e1.printStackTrace();            }            String[] whole = str.split("\n");            String result = whole[whole.length - 1].replace("`", "");            String[] total = result.split(",");            log.info("The response XML of micro pay is:{}", result);            log.info("The response XML of micro pay is:{}", total);            return (SwiftPassMicroPayBaseResult) xstream.fromXML(xml, new SwiftPassMicroPayBaseResult());        } catch (ResourceAccessException e) {            // IO error            // 支付结果未知，将订单id加入轮训队列            aliyunMNSSend.sendClint(order.getId());            throw new RuntimeException("支付结果未知，请稍后到订单列表中查看结果");        }    }    public String getBody(Order order) {        StringBuffer stringBuffer = new StringBuffer();        if (order.getType() == OrderType.MEMBER_DEPOSIT) {            stringBuffer.append("会员充值");        } else {            order.getItems().forEach(e ->                    stringBuffer.append(e.getQuantity() + "个" + e.getProductName() + "")            );        }        return Stringutil.cutStr(stringBuffer.toString(), 120);    }    public String getRewardBody(Reward reward) {        StringBuffer stringBuffer = new StringBuffer();        stringBuffer.append(reward.getCount() + "个" + reward.getProductName() + "");        return Stringutil.cutStr(stringBuffer.toString(), 120);    }    private String getStockOrderBody(StockOrder reward) {        StringBuffer stringBuffer = new StringBuffer();        reward.getItems().forEach(e ->                stringBuffer.append(e.getQty() + "个" + e.getProductName() + ""));        return Stringutil.cutStr(stringBuffer.toString(), 120);    }    private String getCallTranBody(CallTran callTran) {        StringBuffer stringBuffer = new StringBuffer();        stringBuffer.append(callTran.getCount() + "个" + callTran.getProductName() + "");        return Stringutil.cutStr(stringBuffer.toString(), 120);    }    @Autowired    public void setJdbc(JdbcTemplate jdbc) {        this.jdbc = jdbc;    }    @Autowired    public void setTransactoinTemplate(TransactionTemplate transactoinTemplate) {        this.transactoinTemplate = transactoinTemplate;    }    @Autowired    public void setStockService(StockService stockService) {        this.stockService = stockService;    }    @Autowired    public void setMemberDao(MemberDao memberDao) {        this.memberDao = memberDao;    }    @Autowired    public void setMemberAccountDao(MemberAccountDao memberAccountDao) {        this.memberAccountDao = memberAccountDao;    }    @Autowired    public void setSimpMessagingTemplate(SimpMessagingTemplate simpMessagingTemplate) {        this.simpMessagingTemplate = simpMessagingTemplate;    }    @Autowired    public void setXstream(XStream xstream) {        this.xstream = xstream;    }    @Autowired    public void setObjectMapper(ObjectMapper objectMapper) {        this.objectMapper = objectMapper;    }    @Autowired    public void setPaymentDao(PaymentDao paymentDao) {        this.paymentDao = paymentDao;    }    @Autowired    public void setOrderDao(OrderDao orderDao) {        this.orderDao = orderDao;    }    @Autowired    public void setMemberService(MemberService memberService) {        this.memberService = memberService;    }    @Autowired    public void setStoreDao(StoreDao storeDao) {        this.storeDao = storeDao;    }    @Autowired    public void setWechatTemplateService(WechatTemplateService wechatTemplateService) {        this.wechatTemplateService = wechatTemplateService;    }    @Autowired    public void setAliyunMNSSend(AliyunMNSSend aliyunMNSSend) {        this.aliyunMNSSend = aliyunMNSSend;    }    @Autowired    public void setRestTemplate(RestTemplate restTemplate) {        this.restTemplate = restTemplate;    }    @Autowired    public void setMemberAccountTransactionDao(MemberAccountTransactionDao memberAccountTransactionDao) {        this.memberAccountTransactionDao = memberAccountTransactionDao;    }    @Autowired    public void setStockTransactionService(StockTransactionService stockTransactionService) {        this.stockTransactionService = stockTransactionService;    }    @Autowired    public void setMemberAccountService(MemberAccountService memberAccountService) {        this.memberAccountService = memberAccountService;    }    public Order GetNegativeOrder(Order order) {        //生成负订单        Order refundOrder = new Order();        BeanUtils.copyProperties(order, refundOrder);        refundOrder.setId(UuidUtil.getUuid());        refundOrder.setStatus(OrderStatus.FINISHED);        refundOrder.setCreateTime(new Date());        refundOrder.setRefOrderId(order.getId());        refundOrder.setCount(-order.getCount());        refundOrder.setAmount(-order.getAmount());        refundOrder.setTotal(-order.getTotal());        refundOrder.setCode(Md5Util.encrypt16(refundOrder.getId()));        refundOrder.setCommission(-order.getCommission());        refundOrder.setPaymentTime(new Date());        //原订单        List<OrderItem> originalOrderItem = order.getItems();        //生成后的退款订单明细        List<OrderItem> refundItem = new ArrayList<>();        Map<String, String> map = new HashMap();        for (OrderItem i : originalOrderItem) {            OrderItem item = new OrderItem();            BeanUtils.copyProperties(i, item);            item.setId(UuidUtil.getUuid());            item.setQuantity(-1 * i.getQuantity());            item.setCommission(-1 * i.getCommission());            item.setDealPrice(-1 * i.getDealPrice());            refundItem.add(item);            map.put(i.getId(), item.getId());        }        for (OrderItem orderItem : refundItem) {            if (!StringUtils.isBlank(orderItem.getMasterItemId())) {                orderItem.setMasterItemId(map.get(orderItem.getMasterItemId()));            }        }        refundOrder.setItems(refundItem);        return refundOrder;    }    @Override    public void notifyRewardNewCallService(Reward reward, String mark) {        if (redisService.canProceedCustom("notify" + reward.getId(), 24 * 60 * 60)) {            Employee employee = e.findOne(reward.getEmpId());            try {                Map<String, String> map = new HashMap<>();                map.put("tableNum", reward.getTableNo());                map.put("empCode", employee.getCode());                map.put("productName", reward.getProductName());                map.put("qty", String.valueOf(reward.getCount()));                map.put("empName", reward.getEmpName());                map.put("storeId", reward.getStoreId());                map.put("type", "REWARD");                map.put("mark", mark);                putWs(map);            } catch (Exception e) {                log.warn("Fail to send websocket notify to store:{}", reward.getStoreId());            }        }    }}